package com.test.tinyurl.util;

import org.apache.commons.collections4.MapUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Map;

/**
 * 视图工具类
 */
public final class ViewUtil {

    /**
     * 转发
     */
    public static final String FORWARD = "forward:";

    /**
     * 重定向
     */
    public static final String REDIRECT = "redirect:";

    /**
     * 构建返回视图
     *
     * @param name   视图名称
     * @param params 返回参数
     * @return
     */
    public static ModelAndView buildDefault(String name, Map<String, Object> params) {
        ModelAndView view = new ModelAndView(name);
        if (MapUtils.isNotEmpty(params)) {
            for (Map.Entry<String, Object> param : params.entrySet()) {
                view.addObject(param.getKey(), param.getValue());
            }
        }
        return view;
    }

    /**
     * 构建返回视图
     *
     * @param name   视图名称
     * @param params 返回参数
     * @return
     */
    public static ModelAndView buildForward(String name, Map<String, Object> params) {
        ModelAndView view = new ModelAndView(ViewUtil.FORWARD.concat(name));
        if (MapUtils.isNotEmpty(params)) {
            for (Map.Entry<String, Object> param : params.entrySet()) {
                view.addObject(param.getKey(), param.getValue());
            }
        }
        return view;
    }

    /**
     * 构建返回视图
     *
     * @param name   视图名称
     * @param params 返回参数
     * @return
     */
    public static ModelAndView buildRedirect(String name, Map<String, Object> params) {
        ModelAndView view = new ModelAndView(ViewUtil.REDIRECT.concat(name));
        if (MapUtils.isNotEmpty(params)) {
            for (Map.Entry<String, Object> param : params.entrySet()) {
                view.addObject(param.getKey(), param.getValue());
            }
        }
        return view;
    }

    /**
     * 构建返回视图
     *
     * @param name   视图名称
     * @param params 返回参数
     * @return
     */
    public static ModelAndView buildRedirectLogin(String name, Map<String, Object> params,
                                                  RedirectAttributes redirectAttributes) {
        ModelAndView view = new ModelAndView(ViewUtil.REDIRECT.concat(name));
        if (MapUtils.isNotEmpty(params)) {
            for (Map.Entry<String, Object> param : params.entrySet()) {
                redirectAttributes.addFlashAttribute(param.getKey(), param.getValue());
            }
        }
        return view;
    }
}
